import { WeaLocaleProvider,WeaFormItem,WeaInput,WeaTools } from "ecCom";
import { Modal, Radio } from 'antd';
const RadioGroup = Radio.Group;
import { modeForm } from './excelUtil';
const getLabel = WeaLocaleProvider.getLabel;
import jQuery from 'jquery';

export const showExportMenu = (datas, billsid, modeid,type,comefrom,modeCustomid,dataKey,expcardname,layoutid?,callBack?:Function) => {
    let {isExpOne=''} = expcardname;
    showModal(getLabel(17416, '导出'), (
      <div style={{ minHeight: 100,maxHeight:400,overflow:"scroll", margin: "-30px -50px",textAlign:'center', }}>
            { isExpOne == ''?<RadioGroup
                onChange={(e) => {
                    localStorage.setItem("cube_export_type", e.target.value);
                }}
                defaultValue={datas[0]['key'] || ""}
            >
                {getRadioGroup(datas)}
            </RadioGroup>:''}
            {expcardname&&expcardname.key=="1"?<WeaFormItem  
                style = {datas.length>1?{top:'0px'}:{top:'30px'}}
                label={getLabel(17517, '文件名称')}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 16 }}
                width = {"20%"}
            >
            <div>
             <WeaInput value={expcardname.showname}  width = {"60%"} onChange={(e) => {
                    localStorage.setItem("cube_export_name", e);
                }}/>
            </div>
            </WeaFormItem>:""}
        </div>
    ), 400, billsid, modeid,layoutid?layoutid:'0',type,comefrom,modeCustomid,dataKey,isExpOne,callBack);
}
const getRadioGroup = (datas = []) => {
    const radioArr: any = [];
    const radioStyle = {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
        marginLeft: "10px",
    };
    for (let i = 0; i < datas.length; i++) {
        const item: any = datas[i];
        radioArr.push(<Radio style={radioStyle} key={item.key} value={item.key}>{item.showname}</Radio>)
    }
    return radioArr;
}

const showModal = (title,content, width: number = 400, billsid, modeid,layoutid,type,comefrom="",modeCustomid="",dataKey="",isExpOne="",callBack?:Function) => {
    Modal.info({
        title: <span><div className='wea-browser-single-icon-circle' style={{ background: "#96358a" }}><i className='icon-coms-ModelingEngine' /></div>{title}</span>,
        content: content,
        iconType: "",
        okText: getLabel(33703, "确认"),
        width: width,
        onOk() {
            if(type === "list"){
                if(localStorage.getItem("cube_export_type")=="list"||isExpOne=="1"){   //如果选择的是列表EXCEL列表文件，走老的导出   ,当后台设置了一种导出类型的时候直接导出
                   let excelName = localStorage.getItem("cube_export_name");
                   typeof callBack =="function" && callBack(billsid,excelName);
                   return;
                }
                formPost("/weaver/weaver.formmode.expcard.servlet.ExpCardServer",{
                    action:"expbatchcard",
                    fileType:localStorage.getItem("cube_export_type"),
                    billids:billsid,
                    modeId:modeid,
                    excelName:localStorage.getItem("cube_export_name"),
                    comefrom:comefrom,
                    modeCustomid:modeCustomid,
                    dataKey:dataKey
                });
            }else if(type==="card"){                
                formPost("/weaver/weaver.formmode.expcard.servlet.ExpCardServer",{
                    action:"expcard",
                    fileType:localStorage.getItem("cube_export_type"),
                    billid:billsid,
                    layoutid:layoutid,
                    modeId:modeid,
                    doInterface:1
                });
            }
            setTimeout(() => {
                localStorage.setItem("cube_export_type", "");
                localStorage.setItem("cube_export_name", "");
            }, 500)
        },
    });
}

export const  formPost=(URL="", PARAMTERS={})=> {
    //创建form表单
    var temp_form = document.createElement("form");
    temp_form.action = URL;
    //如需打开新窗口，form的target属性要设置为'_blank'
    temp_form.target = "_self";
    temp_form.method = "post";
    temp_form.style.display = "none";
    //添加参数
    for (let item in PARAMTERS) {
        let opt = document.createElement("input");
        opt.name = item;
        opt.value = PARAMTERS[item];
        temp_form.appendChild(opt);
    }
    document.body.appendChild(temp_form);
    //提交数据
    temp_form.submit();
}


//自定义注册事件校验
export const verifyCustomRegisterEvent = (params, callback, registerFnParams={}) => {
    let result = null;
    const opertype = convertOpertype(params);
    const eventArr = opertype === null ? new Array() : modeForm.eventList[opertype];
    //存在注册事件
    if (typeof eventArr === "object" && eventArr.length > 0) {
        let index = 0;
        const executeVerify = () => {
            if (index < eventArr.length) {
                eventArr[index++](() => {
                    executeVerify();
                }, registerFnParams);
            } else {
                result = callback();
            }
        }
        executeVerify();
    } else {
        result = callback();
    }
    return result;
}

const convertOpertype = (params) => {
    if (typeof params === "string")
        return params;
    
    return null;
}

export const showExpendError = (pageExpendResult,href)=>{
    let content:any=[];
    let orihref=href;
    for(let data in pageExpendResult.errordata){
        let pcontent=`${getLabel('512681','执行{0}出错').replace(/\{0\}/,data)},${getLabel('512682','数据id为')}:${pageExpendResult.errordata[data]}`;
        let a=<a href={orihref+"expanderrorid="+pageExpendResult.errordata[data]} target="_blank" style={{marginLeft:10,verticalAlign:'middle'}}>{getLabel('385156','查看列表') }</a>
        content.push(<p style={{textAlign:'center'}}>
            <span title={pcontent} style={{textAlign:'left',width:'300px',overflow:'hidden',textOverflow:'ellipsis',display:'inline-block',whiteSpace:'nowrap',verticalAlign:'middle'}}>{pcontent}</span>
            {a}</p>);
    }
    Modal.error({
        width:500,
        content:content
    })
}

/**
 * 
 * @param pageExpendResult 明细表是否要拖动
 * @param href 
 */
export const isDragula = (card,detail)=>{
    const type=card.base.type=='2'||card.base.type=='1';
    const detailtable=card.getDetailTable(detail);
    const excel = card.modeExcel.getExcel(detail);
    const { isPagination = false } = excel.detailProps;
    const isNeedPagination = (card.base.type == '0' || card.base.type == '1' || card.base.type == '2') && isPagination;
    let result = type&&detailtable.isOpenCustomOrder&&!isNeedPagination;
    return result;
}

/**
 * 是否来自门户菜单点击
 */
export const isFromProtal=()=>{
    let url=WeaTools.WindowFunc.getTop().location.href;
    if(url.indexOf('/spa/cube/')>0){
        return false;
    }
    return true;
}


//滚动过程中控制表头固定
export const fixedDetailHead = () =>{
    const container = jQuery('.cube-card-form-content');
    const conOffsetTop = container.offset().top;
    container.find(".excelDetailTableDiv").each(function(){
        const groupid = jQuery(this).attr("data-groupid");
        const detailFixedDiv = jQuery(this).find("[class^=excelDetailFixedHead]");
        const detailTable = jQuery("#oTable"+groupid);
        const lockedBtn = jQuery(this).parent().find(".cube-detail-locked-btnrow");
        const existLockedBtn = lockedBtn.length > 0;
        let detailHeight = detailTable.height();
        const unFixedFn = () =>{
            if(existLockedBtn)
                lockedBtn.removeClass("cube-detail-locked-btnrow-fixed");
            detailFixedDiv.hide();
        }
        if(detailHeight < 300){     //此if不能后移，会导致部分ios滑动闪屏，why...
            unFixedFn();
            return true;
        }
        let detailOffsetTop = detailTable.offset().top;
        let fixedHeadHeight = detailFixedDiv.height();
        let lockedBtnHeight = 0;
        if(existLockedBtn){
            lockedBtnHeight = lockedBtn.height();
            detailHeight += lockedBtnHeight;
            fixedHeadHeight += lockedBtnHeight;
        }
        const fixedFn = () =>{
            if(existLockedBtn){
                lockedBtn.addClass("cube-detail-locked-btnrow-fixed");
                lockedBtn.find(".cube-detail-locked-btnrow-content").css("top", conOffsetTop);
            }
            detailFixedDiv.css("top", conOffsetTop+lockedBtnHeight).show();
            syncFixedHeadWidth(groupid);
            syncDetailScrollXPosition(groupid);
        }
        //冻结表头，明细表最低要求200px高度
        //console.log("groupid",groupid,"detailHeight",detailHeight,"detailOffsetTop",detailOffsetTop,"conOffsetTop",conOffsetTop,"fixedHeadHeight",fixedHeadHeight);
        if(detailOffsetTop < conOffsetTop && detailOffsetTop + detailHeight >= fixedHeadHeight + conOffsetTop){
            fixedFn();
        }else{
            unFixedFn();
        }
    });
}


//同步列宽到固定表头,列锁定情况仅同步滚动区域
export const syncFixedHeadWidth = (groupid) => {
    try{
        const detailTable = jQuery("#oTable"+groupid);
        const detailFixedTable = jQuery("#oTable"+groupid+"_head");
        const detailFixedDiv = detailFixedTable.parent();
        if(!detailFixedDiv.is(":hidden")){
            detailFixedTable.width(detailTable.width());
            // const fixedWidthRow = detailFixedTable.find("tr.detailControlWidth");
            // detailTable.find("tr.detailControlWidth").children().each(function(index){
            //     fixedWidthRow.find("td:eq("+index+")").css("width", jQuery(this).width()+"px");
            // });
            detailFixedDiv.css("width", detailFixedDiv.parent().width());
        }
    }catch(e){}
}

//同步横向滚动条位置到固定表头
export const syncDetailScrollXPosition = (groupid) => {
    try{
        const detailArea = (window as any).jQuery("#dTableArea_"+groupid);
        detailArea.find(".excelDetailFixedHead").scrollLeft(detailArea.find(".excelDetailTable_wrap").scrollLeft());
    }catch(e){}
}


//计算指定区域下明细表样式，兼容标签页内嵌明细情况
export const calculateDetailAreaStyle = (area=jQuery()) =>{
    area.find(".cube-detail").each(function(){
        if(!jQuery(this).is(":visible"))
            return true;
        // const excelDetailTableDiv = jQuery(this).find(".excelDetailTableDiv");
        // const groupid = parseInt(excelDetailTableDiv.attr("data-groupid"));
        // const swapWidth = excelDetailTableDiv.width();
        // const dataAreaWidth = excelDetailTableDiv.find("#oTable"+groupid).width();
        // // const lockedAreaWidth = excelDetailTableDiv.find("#oTable"+groupid+"_locked") && excelDetailTableDiv.find("#oTable"+groupid+"_locked").width() || 0;
        // const detailObj = detailMap.get("detail_"+(groupid+1));
        // if(swapWidth >=dataAreaWidth ){     //宽度不足，横向滚动条失效
        //     detailObj.controlVariableMap("forceDisabledScrollX", true);
        // }
        const lockedBtnRow = jQuery(this).find(".cube-detail-locked-btnrow");
        if(lockedBtnRow.length > 0){
            const topRowHeight = lockedBtnRow.height();
            const topRowWidth = lockedBtnRow.parent().width();
            lockedBtnRow.find(".cube-detail-locked-btnrow-content").width(topRowWidth);
            lockedBtnRow.find(".cube-detail-locked-btnrow-placeholder").height(topRowHeight);
        }
        // syncLockedForDidMount(groupid);
    });
}

export const importantParamRange = ["token", "billid","type","modeId","formId","customid","layoutid", "isFormMode", "iscreate", "src",
    "currentLayoutId","pageexpandid","JSONStr","btntype","issystemflag","oldmodedatastatus"
];